package com.aixin.csopuser.utils;

import com.github.pagehelper.PageInfo;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.util.List;
import java.util.Optional;

public class ResponseUtils {

    public static <T> PageInfo<T> makePageInfo(Page<T> page) {
        return makePageInfo(page, page.getContent());
    }

    public static <T> PageInfo<T> makePageInfo(Page<T> page, List<T> list) {
        PageInfo<T> pageInfo = new PageInfo<>();
        pageInfo.setList(page.getContent());
        pageInfo.setTotal(page.getTotalElements());
        pageInfo.setPages(page.getTotalPages());
        pageInfo.setPageSize(page.getSize());
        pageInfo.setPageNum(page.getNumber());
        pageInfo.setIsFirstPage(page.isFirst());
        pageInfo.setIsLastPage(page.isLast());
        pageInfo.setHasNextPage(page.hasNext());
        pageInfo.setHasPreviousPage(page.hasPrevious());

        return pageInfo;
    }

    public static <T> PageInfo<T> makePageInfo(Long total, Integer pageNum, Integer pageSize, List<T> list) {
        PageInfo<T> pageInfo = new PageInfo<>();
        pageInfo.setList(list);
        pageInfo.setTotal(total);
        pageInfo.setPages(new Double((total + pageSize - 1) / pageSize).intValue());
        pageInfo.setPageSize(pageSize);
        pageInfo.setPageNum(pageNum);
//        pageInfo.setIsFirstPage(page.isFirst());
//        pageInfo.setIsLastPage(page.isLast());
//        pageInfo.setHasNextPage(page.hasNext());
//        pageInfo.setHasPreviousPage(page.hasPrevious());

        return pageInfo;
    }

    public static <X> ResponseEntity<X> wrapOrNotFound(Optional<X> maybeResponse) {
        return wrapOrNotFound(maybeResponse, (HttpHeaders)null);
    }

    public static <X> ResponseEntity<X> wrapOrNotFound(Optional<X> maybeResponse, HttpHeaders header) {
        return (ResponseEntity)maybeResponse.map((response) -> {
            return ((ResponseEntity.BodyBuilder)ResponseEntity.ok().headers(header)).body(response);
        }).orElse(new ResponseEntity(HttpStatus.NOT_FOUND));
    }
}
